<?php

    // Игровая форма
    class game_form
    {
        private $values = Array();
        private $id = null;
        private $Executed = false;
        public $gameobject; // = GAME;
        private $t0; // = html_table;
        private $StatusMessages = Array();
        private $gameclass; // GAME

        public $Status = 0;

        private $LoseMessage = 'You lose!';
        private $WinMessage = 'You win!';

        private $Buttons = Array();
        
        function OpenGame($gameid, $gameclass)
        {
            $mikron->Page->StartBody();
            $this->gameclass = $gameclass;
            $this->start();
            $this->begin();
            $gameclass->Play();
            $this->Stop();
        }

        private function Stop()
        {
            $this->end(false);
            $mikron->Page->EndBody();
            exit;
        }
        
        /**
        * Меню формы, которое затем выводится функцией DrawButtons()
        * 
        * @param mixed $id
        * @param mixed $iconindex Индекс изображения кнопки (отсчет по вертикали, размер 24x24 пиксела)
        * @param mixed $text Текст справа от иконки
        * @param mixed $link Ссылка для кнопки
        * @param mixed $javascript
        * @param mixed $disabled Заблокированное состояние
        * @param mixed $visible Видимость true/false
        */
        function AddButton($id, $iconindex=null, $text=null, $link=null, $javascript=null, $disabled=false, $visible = true)
        {
            $this->Buttons[$id] = Array("iconindex"=>$iconindex, "text"=>$text, "link"=>$link, "javascript"=>$javascript, "disabled"=>$disabled, "visible"=>$visible);
        }

        function AddStatus($code, $message)
        {
            $this->StatusMessages[$code] = $message;
        }

        function IsExecuted()
        {
            return $this->Executed;
        }

        private function ShowStatus()
        {
            if(!is_null($message = $this->getMessageByCode($this->Status)))
            {
                ?>
                <div onclick="this.style.display='none';" style="position: absolute; background-color: #fff; width: 200px; padding: .5em;
                top: 320px; left: 347px; text-align: left; opacity: .9;  ">
                    <h1>Результат</h1>
                    <?php echo $message; ?>
                    <p style="margin-bottom: 0px; "><font class="disabledtext" style="font-size: 7pt; ">Кликните
                    на сообщении, чтобы его скрыть.</font></p>
                </div>
                <?php
            }
        }

        private function getMessageByCode($code)
        {
            if(array_key_exists($code, $this->StatusMessages))
            {
                return $this->StatusMessages[$code];
            }
            else
            {
                return null;
            }
        }

        public function __get($name)
        {
            if($this->Exists($name))
            {
                return $this->values[$name]['value'];
            }
            else
            {
                throw new Exception("Ошибка чтения поля $name в игровой форме.");
            }
        }

        public function __set($name, $value)
        {
            if($this->Exists($name))
            {
                $this->values[$name]['value'] = $value;
                if(!is_null($value))
                {
                    switch($type = $this->values[$name]['value'])
                    {
                        case 'int':
                            if(!is_numeric($value))
                            {
                                throw new Exception('Ошибка в игровой форме');
                            }
                            break;
                    }
                }
            }
            else
            {
                throw new Exception("Ошибка записи поля $name в игровой форме.");
            }
        }

        function __construct($id)
        {
            $this->id = (int)$id;
            $this->addIntValue("formid", true);
            $this->formid = $this->id;
            $this->addStringValue("rate", true);

            try
            {
                // Загрузка игры
                $gameobjectID = (int)$id;
                $this->gameobject = new GAME($gameobjectID);
                $this->AddStatus(1, 'У Вас недостаточно «шансов» для игры.');
                $this->AddStatus(2, $this->WinMessage);
                $this->AddStatus(3, $this->LoseMessage);
                // $this->AddButton("help", 0, "Правила", "/rules/#".$this->gameobject->code->value);
            }
            catch(Exception $ex)
            {
                ob_clean();
                header('Location: /cabinet/');
                exit;
            }
        }

        function start()
        {
            global $mikron;
            if(isset($_REQUEST['gameform']))
            {
                $gf = $_REQUEST['gameform'];
                if(is_array($gf))
                {
                    if(isset($gf['formid']))
                    {
                        if(($id = (int)$gf['formid'])== $this->id)
                        {
                            $this->Executed = true;
                            foreach($gf as $key => $value)
                            {
                                $this->$key = $value;
                            }
                        }
                    }
                }
            }
        }

        private function Exists($name)
        {
            return array_key_exists($name, $this->values);
        }

        function addStringValue($name, $hidden = true)
        {
            $this->AddValue($name, $hidden, "string");
        }
    
        function addIntValue($name, $hidden = true)
        {
            $this->AddValue($name, $hidden, "int");
        }

        private function AddValue($name, $hidden = true, $type)
        {
            if(array_key_exists($name, $this->values))
            {
                throw new Exception("Ошибка в игровой форме. Дубликат поля $name.");
            }
            // Сoхранение информации о поле
            $this->values[$name] = Array("hidden"=>$hidden, "type"=>"int", "value"=>null);
        }

        private function show($showrates = true)
        {
            global $mikron;
            $t1 = new html_table(null, null, null);
            $t1->newcol(null, true, true);
                $t2 = new html_table(null, null, '10%');
                $t2->newcol(null, false, true, null, null, '100');
                    if($showrates)
                    {
                        $formuri = $_SERVER['REQUEST_URI'];
                        if(($pos = strpos($formuri, '?')) !== false)
                        {
                            $formuri = substr($formuri, 0, $pos);
                        }
                        ?>
                        <form action="<?php echo $formuri; ?>" method="post" id="gameform" style="margin: 0px; padding: 0px; text-align: center; ">
                        
                        <div style="text-align: center; padding-left: 1em; display: table;">
                            <?php
                            /*$otherchances = Array();
                            // Вычитка элемента магазина (ставки-фишки)
                            $mitems = $mikron->Queries->Query('MARKET_ITEM', null, new Criterion('forsale', 1));
                            while($mi = $mitems->fetch())
                            {
                                if($mi->code->value == $rate)
                                {
                                    ?>
                                    <table border="0" width="100%">
                                        <tr>
                                            <td colspan="3" align="center">
                                                <h1>Сейчас Вы<br />играете на:<br />&darr;</h1>
                                                <div class="chip_<?php echo $mi->code->value; ?>"></div>
                                                <?php echo $mi->title->value; ?>
                                            </td>
                                        </tr>
                                    </table>
                                    <?php
                                }
                                else
                                {
                                    $code = $mi->code->value;
                                    $otherchances[] = $mi;
                                }
                            }
                            if(count($otherchances) > 2)
                            {
                                ?>
                                    <a id="changelink" onclick="this.style.display='none';openchances(); return false;" href="<?php echo $_SERVER['REQUEST_URI']; ?>&change">Изменить</a>
                                    <table  width="100%" id="chances" style="display: none; border: none; " cellspacing="2">
                                        <?php
                                            foreach($otherchances as $oc)
                                            {
                                                $code = $oc->code->value;
                                                $name = $oc->title->value;
                                                $picture = $oc->picture->value;
                                                ?><tr><td style="text-align: center; background-color: #eee; padding: .2em; "><?php
                                                $id = $this->gameobject->id;
                                                $rate = $this->rate;
                                                $link = "game=".$id."&$code";
                                                echo "<a onclick=\"ajaxRefreshGameForm('/cabinet/games/treasure/index.php', '$link&ajax=yes', 'gameformdiv');
                                                    location.href='#$code'; return false;\"
                                                    href='?$link'><img src=\"$picture\"><br />$name</a><br />";
                                                ?></td></tr><?php
                                            }
                                        ?>
                                    </table>
                                <?php
                            }
                            */
                            foreach($this->values as $name => $v)
                            {
                                $type = $v['hidden']?"hidden":"checkbox";
                                $inpname = "gameform[".$name."]";
                                $value = $this->values[$name]['value'];
                                echo sprintf('<input type="%s" name="%s" size="%s" value="%s" />', $type, $inpname, 2, $value);
                            }
                            ?>
                            <?php $this->ShowStatus(); ?>

                            </div>
                        </form>
                        <?php /*** АНТИЧИТЕР ***/ ?>
                        <script type="text/javascript">
                            var usersession_object = document.getElementsByName('gameform[usersession]')[0];
                            if(window.parent.frames.length == 0)
                            {
                                usersession_object.value = 0;
                            }
                            else
                            {
                                usersession_object.value = '(' + window.parent.frames.length + ')' + window.parent.location.toString();
                            }
                        </script>
                        <?php
                    }
            $t2->end();
            $t1->end();
            return true;
        }

        function Played($cabinet, $is_win, $lose_quantity, $win_quantity)
        {
            $style = $is_win?"_blue":"_silver";
            $message = $is_win?$this->WinMessage:$this->LoseMessage;
            $source = $is_win?9:10;
            $rate = $this->values['rate']['value'];
            $amount = 0;
            $cabinet_rate_value = $cabinet->$rate->value;
            if($cabinet_rate_value < $lose_quantity)
            {
                $this->Status = 1;
                throw new Exception('{{$NO_CHANCES}}');
                return null;
            }
            $platinum = $rate=="platinum" ? $is_win?$win_quantity-1:-$lose_quantity : 0;
            $gold = $rate=="gold" ? $is_win?$win_quantity-1:-$lose_quantity : 0;
            $silver = $rate=="silver" ? $is_win?$win_quantity-1:-$lose_quantity : 0;
            $bronze = $rate=="bronze" ? $is_win?$win_quantity-1:-$lose_quantity : 0;
            $foplog = ChangeCabinetBalance($cabinet, $source, $amount, $platinum, $gold, $silver, $bronze);
            if($cabinet->$rate->value < 0)
            {
                $this->Status = 1;
                $cabinet->$rate->value = $cabinet_rate_value;
                throw new Exception('{{$NO_CHANCES}}');
                return null;
            }
            OperationLogEcp($foplog, $cabinet);
            return $foplog;
        }

        public function begin()
        {
            global $t0, $mikron;
            ?>
            <script type="text/javascript">

                // var changelink = document.getElementById("changelink");
                // changelink.style.display = '';
                function openchances()
                {
                    // var ochances = $('chances');
                    var ochances = document.getElementById('chances');
                    ochances.style.display = '';
                }
                /* AJAX */
                function ajaxRefreshGameForm(url, parameters, container_id)
                {
                    var container = document.getElementById(container_id);
                    getDataAjax2(url, container, parameters, parseContents);
                    return false;
                }
                // получение данных, используя AJAX
                // здесь реализовано на jquery, но можно и  по другому
                function getDataAjax2(url, container, data, fnctn)
                {
                    $.ajax({type: "GET", url: url, data: data, success: function(data) {fnctn(data, container);}});
                }
                function parseContents(data, container)
                {
                    container.innerHTML = data;
                    return true;
                }
                function PlayGame()
                {
                    gameform.submit();
                    return false;
                    var pb = document.getElementById('playbutton');
                    pb.style.display = 'none';
                    var wi = document.getElementById('waitimage');
                    wi.style.display = '';
                    // готовим объект
                    var options = {
                      target: "#gameformdiv",
                      url: "index.php?ajax=true&game=<?php echo $this->gameobject->id; ?>&<?php echo $this->rate; ?>",
                      type: "POST",
                      complete: function(data, textStatus)
                      {
                            updatebank();
                      }
                    }; 
                    $("#gameform").ajaxSubmit(options);
                }
                // Обновление банка
                function updatebank()
                {
                    ajaxRefreshGameForm("/getbank.php?ajax=true", "ajax=true", "userbankdiv");
                }
            </script>
            <?php
            if(isset($_GET['ajax']))
            {
                ob_clean();
            }
            ?>
            <div id="gameformdiv" style="display: table-cell; ">
            <div class="gamebox" style="display: table-cell; " s tyle="background-color: #fff; display: table; overflow: hidden; 
                -moz-opacity: 0.25;
                -khtml-opacity: 0.25;
                opacity: 0.25;">
           {{nicewindow style=games caption="<nobr><h1>Игра <?php echo $this->gameobject->name->value; ?> — выигрыш <?php echo round($this->gameobject->prize->value/100,2); ?> руб.</h1><nobr>"}}
           <?php $this->DrawButtons(); ?>
           <?php
            $t0 = new html_table(null, null, '100%');
            $t0->newcol();
        }

        public function showInstructions()
        {
            if(is_null($this->gameobject->rules->value))
            {
                return false;
            }
            echo "{{nicewindow style=help caption=Информация width=\"60%\"}}";
            echo $this->gameobject->rules->value;
            echo "{{/nicewindow}}";
        }

        public function end($showrates = true)
        {
                global $mikron, $gameform, $t0;
                if(!is_null($this->gameclass))
                {
                    $this->gameid = $this->gameclass->id;
                }
                $this->showInstructions();
            $t0->newcol(null, true, false, null, null, null, "top");
                try
                {
                    $this->show($showrates);
                }
                catch(Exception $ex)
                {
                    $message = "Ошибка при запуске игры. ".$ex->getMessage();
                    echo $message;
                }
            $t0->end();
            ?>
            {{/nicewindow}}
            </div>
            </div>
            <?php
            if(isset($_GET['ajax']))
            {
                $mikron->Page->EndBody(false);
                exit;
            }
        }
        
        private function DrawButtons()
        {

            global $mikron;
            $styles = Array();
            foreach($this->Buttons as $id => $button)
            {
                $iconindex = $button['iconindex'];
                $iconY = -$iconindex * 24;
                $text = $button['text'];
                $link = $button['link'];
                $javascript = $button['javascript'];
                $disabled = (int)$button['disabled']?true:false;
                // $styles[] = ".$id {background: url(menuicons.gif); background-position: 0 $iconY; background-repeat:  no-repeat; }";
            }

            // Добавление необходимого CSS стиля
            $myCSS = ".gamemenu td {background-repeat: no-repeat; height: 24px; }

                \r\n".
                implode("\r\n", $styles)
                .".gamemenu a {display: block; height: 16px; padding-left: 26px; font-size: 0.9em; }
                .gamemenu font {display: block; height: 16px; padding-left: 26px; color: #bbb; font-size: 0.9em; }";
            $mikron->CSS->Add($myCSS, "Game form styles");

            ?>
            <table class="gamemenu" cellspacing="8" border="0">
                <tr>
                    <?php
                    foreach($this->Buttons as $id => $button)
                    {
                        $text = $button['text'];
                        $link = $button['link'];
                        $javascript = $button['javascript'];
                        $disabled = (int)$button['disabled']?true:false;
                        $visible = (int)$button['visible']?true:false;
                        $style = null;
                        if(!$visible)
                        {
                            $style = " style=\"display:none\" ";
                        }
                        if($disabled)
                        {
                            echo sprintf("<td id=\"%s\" %s class=\"%s\"><font>%s</font></td>", $id, $style, $id.'_button', $text);
                        }
                        else
                        {
                            echo sprintf("<td id=\"%s\" %s class=\"%s\" nowrap style=\"white-space: nowrap; \"><a href=\"%s\" %s>%s</a></td>", $id, $style, $id.'_button', $link, $javascript, $text);
                        }
                    }
                    ?>
                </tr>
            </table>
            <?php
        }
    }
    
?>